import tkinter as tk
from tkinter import messagebox, filedialog
import random
import openpyxl

# 全局变量
participants = []  # 存储所有参与者
remaining_participants = []  # 存储剩余未中奖的参与者
winners = []  # 存储已中奖的参与者
running = False  # 控制抽奖过程的状态
timer_count = 0  # 控制计时器

def load_data():
    """从 Excel 文件加载参与者数据"""
    global participants, remaining_participants
    file_path = filedialog.askopenfilename(
        title="选择Excel文件",
        filetypes=[("Excel文件", "*.xlsx"), ("所有文件", "*.*")]
    )
    if not file_path:
        return

    try:
        workbook = openpyxl.load_workbook(file_path)
        sheet = workbook.active
        participants = []
        for row in sheet.iter_rows(min_row=2, values_only=True):  # 假设第一行为标题
            name, department = row
            if name and department:
                participants.append({"name": name, "department": department})
        remaining_participants = participants.copy()
        update_remaining_label()
        messagebox.showinfo("加载成功", f"成功加载 {len(participants)} 条数据！")
    except Exception as e:
        messagebox.showerror("加载失败", f"加载数据时发生错误：{e}")

def update_remaining_label():
    """更新剩余参与人数显示"""
    remaining_label.config(
        text=f"剩余参与人数：{len(remaining_participants)}"
    )

def start_lottery():
    """开始抽奖过程"""
    global running, timer_count
    if running:  # 防止重复触发
        return
    if not remaining_participants:
        messagebox.showinfo("抽奖结束", "所有参与者都已抽过奖！")
        return

    running = True
    timer_count = 0  # 重置计时器
    simulate_lottery()

def simulate_lottery():
    """模拟数据快速闪过的抽奖过程"""
    global running, timer_count
    if not running:
        return

    # 随机显示一个参与者
    current_participant = random.choice(remaining_participants)
    result_label.config(
        text=f"姓名：{current_participant['name']}，部门：{current_participant['department']}"
    )

    # 增加计时器
    timer_count += 1
    if timer_count >= 30:  # 30次调用后（约3秒），停止并确定中奖者
        finish_lottery(current_participant)
    else:
        root.after(100, simulate_lottery)  # 每100毫秒更新一次显示

def finish_lottery(winner):
    """确定中奖者并结束抽奖"""
    global running
    running = False  # 停止抽奖过程

    # 将最终中奖者加入名单
    winners.append(winner)
    remaining_participants.remove(winner)

    # 更新中奖者列表和剩余人数
    result_label.config(
        text=f"中奖者：姓名：{winner['name']}，部门：{winner['department']}"
    )
    winners_list.insert(tk.END, f"{winner['name']} - {winner['department']}")
    update_remaining_label()

def reset_lottery():
    """重置抽奖"""
    global remaining_participants, winners, running
    if running:  # 正在抽奖时禁止重置
        return

    remaining_participants = participants.copy()
    winners.clear()
    result_label.config(text="点击按钮抽奖")
    update_remaining_label()
    winners_list.delete(0, tk.END)

# 创建主窗口
root = tk.Tk()
root.title("抽奖程序")

# 设置背景颜色
root.configure(bg="red")

# 创建界面组件
header_label = tk.Label(root, text="🎉 抽奖程序 🎉", font=("Arial", 24, "bold"), pady=10, bg="red", fg="gold")
header_label.pack()

result_label = tk.Label(root, text="点击按钮抽奖", font=("Arial", 18), fg="white", bg="red", pady=10)
result_label.pack()

remaining_label = tk.Label(root, text="剩余参与人数：0", font=("Arial", 14), fg="white", bg="red")
remaining_label.pack()

# 按钮区
button_frame = tk.Frame(root, bg="red")
button_frame.pack(pady=10)

load_button = tk.Button(button_frame, text="加载数据", font=("Arial", 14), command=load_data, bg="gold")
load_button.grid(row=0, column=0, padx=5)

draw_button = tk.Button(button_frame, text="开始抽奖", font=("Arial", 14), command=start_lottery, bg="gold")
draw_button.grid(row=0, column=1, padx=5)

reset_button = tk.Button(button_frame, text="重置抽奖", font=("Arial", 14), command=reset_lottery, bg="gold")
reset_button.grid(row=0, column=2, padx=5)

winners_label = tk.Label(root, text="中奖者名单：", font=("Arial", 16), bg="red", fg="white", pady=10)
winners_label.pack()

winners_list = tk.Listbox(root, font=("Arial", 12), width=40, height=10)
winners_list.pack()

# 运行主循环
root.mainloop()
